#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2019/10/11 16:49
# @Author  : ZRD
# @Site    : 
# @File    : config.py
# @Software: PyCharm

"""
读取配置文件
"""
import yaml
from .log import LOGGER
import os






class Dict(dict):
    """
    将对象转换成属性访问方式
    """
    __setattr__ = dict.__setitem__
    __getattr__ = dict.__getitem__


def dict_to_object(dictObj):
    """
    将对象转换成属性访问方式
    """
    if not isinstance(dictObj, dict):
        return dictObj
    inst = Dict()
    for k, v in dictObj.items():
        inst[k] = dict_to_object(v)
    return inst


"""
读取配置文件
"""


def get_yaml_data(rootpath):
    yaml_path = os.path.join(rootpath, "conf", "agent.yml")
    try:
        with open(yaml_path, 'r', encoding="utf-8") as f:
            data = yaml.safe_load(f.read())
            # 检查配置文件
            if not data.get('version', None):
                raise Exception(f"{yaml_path} 配置文件解析错误: 没有获取到version属性")
            # data.update({"taskdir": os.path.join(rootpath, data.get("tmpdir", None))})
            if data.get('runmodel') == "debug":
                LOGGER.info(f"加载配置信息: {data}")

            return data
    except Exception as e:
        LOGGER.error(f'读取配置文件错误: {e}')
        os._exit(1)
